import { getTableDetailReq } from '@/service/modules/data-manage'
import { TableInfo } from '@/service/modules/data-manage/types'
import { reactive } from 'vue'

export function useTableDetail() {
  const state = reactive({
    tableDetail: null,
    loading: false,
    previewData: {}
  })

  const getTableDetail = async (
    datasourceId: number,
    dbName: string,
    tableName: string
  ) => {
    if (state.loading) return
    state.loading = true
    const res = await getTableDetailReq({
      datasourceId: datasourceId,
      dbName: dbName,
      tableName: tableName
    })
    state.loading = false
    if (res.resp_code === 0) {
      state.tableDetail = res.data as TableInfo
      state.previewData = JSON.parse(state.tableDetail.previewData)
      state.tableDetail?.columns.forEach((item) => {
        item.previewData = state.previewData[item.columnName]
      })
    }
  }

  return {
    state,
    getTableDetail
  }
}
